<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .clearfix::after,.clearfix::before{
            /*设置添加的子元素的内容为空*/
            content: "";
            /*设置添加的子元素为块级元素*/
            display: block;
            /*设置添加的子元素的高度为0*/
            height: 0;
            /*设置添加的子元素看不见*/
            visibility: hidden;
            /*给添加的子元素设置clear: both;*/
            clear: both;
        }

        #room-out-box {
            height: 300px;
            width: 600px;
            overflow-y: auto;
            margin: 0 auto 20px;
            border: 1px solid;
            border-radius: 4px;
        }
        #chat-room {
            width: 100%;
        }
        #chat-room .one-message-box {
            margin-top: 10px;
            margin-bottom: 20px;
        }
        #chat-room .one-message-box.other .user-info,#chat-room .one-message-box.other .message {
            float: left;
        }
        #chat-room .one-message-box.mine .user-info,#chat-room .one-message-box.mine .message {
            float: right;
        }
        #chat-room .one-message-box .user-info {
            display: inline-block;
            width: 40px;
            height: 40px;
            margin: 0 10px ;
            text-align: center;
            font-size: 12px;
            border: 1px solid #999999;
            border-radius: 10px;
        }
        #chat-room .one-message-box .message {
            display: inline-block;
            max-width: 360px;
            text-align: left;
            padding: 5px 10px;
            border: 1px solid;
            border-radius: 10px;
            word-break: break-all;
        }
        #chat-room .connect-message-box {
            text-align: center;
        }
        #chat-room .connect-message-box>span {
            display: inline-block;
            padding: 2px 6px;
            background-color: #999999;
            color: #ffffff;
            font-size: 12px;
            margin: 5px 0;
            border-radius: 4px;
        }
        #chat-input {
            margin-bottom: 10px;
            width: 100%;
            height: 100px;
        }
        .input-box {
            margin: 0 auto;
            width: 600px;
        }
    </style>
</head>
<body>
    <h2 style="text-align: center">websocket（在线人数：<span id="online-number">0</span>）</h2>
    <div id="room-out-box">
        <div id="chat-room"></div>
    </div>
    <div class="input-box">
        <textarea id="chat-input" style="display: block"></textarea>
        <button id="send-btn" type="button">发送</button>
    </div>
</body>
<script th:src="@{/js/jquery-3.6.0.min.js}"></script>
<script th:inline="javascript">
    var sessionId = [[${#request.session.id}]];
    var contextPath = [[${#request.contextPath}]];
    $(function () {
        var protocol = location.protocol.indexOf('https') === -1 ? 'ws' : 'wss';
        var url = protocol + '://' + location.host + contextPath + '/ws/' + sessionId;
        var client = new WebSocket(url);
        client.onopen = function () {
            console.log('websocket连接成功');
        };
        client.onclose = function (e) {
            console.warn(e);
        };
        client.onerror = function (e) {
            console.error(e);
        };
        client.onmessage = function (payload) {
            var message = JSON.parse(payload.data);
            if (message.type === 'online-count') {
                $('#online-number').html(message.message);
            }
            $('#chat-room').append(messageToNode(message));
            $('#room-out-box')[0].scrollTop = $('#chat-room')[0].offsetHeight;
        };

        $('#send-btn').click(function () {
            var message = $.trim($('#chat-input').val());
            if (message) {
                client.send(message);
            }
            $('#chat-input').val('');
        });

        $('#chat-input').on('keyup', function (e) {
            if (e.keyCode === 13) {
                var message = $.trim($('#chat-input').val());
                if (message) {
                    client.send(message);
                }
                $('#chat-input').val('');
            }
        });
    });

    function messageToNode(messageObj) {
        var nodeStr = '';
        if (messageObj.type === 'chat') {
            nodeStr += '<div class="one-message-box clearfix ' + (messageObj.sessionId === sessionId ? 'mine' : 'other') + '">'
            nodeStr += '<div class="user-info">用户' + messageObj.sessionId.replace(/(\w{2})(\w*)(\w{2})/, '$1**$3') + '</div>'
            nodeStr += '<div class="message">' + messageObj.message + '</div>'
            nodeStr += '</div>'
        } else if (messageObj.type === 'connect' || messageObj.type === 'un-connect') {
            var action = '';
            if (messageObj.type === 'connect') {
                action = '加入';
            } else {
                action = '退出';
            }
            nodeStr += '<div class="connect-message-box"><span>用户' + messageObj.sessionId.replace(/(\w{2})(\w*)(\w{2})/, '$1**$3') + action + '聊天室</span></div>'
        }
        return nodeStr;
    }
</script>
</html>
